#pragma once

#include <iterator>

namespace alpha { namespace utility {

inline char hex2ord(char ch)
{
	if (ch >= '0' && ch <= '9')
		return ch - '0';
	else if (ch >= 'a' && ch <= 'f')
		return ch - 'a' + 0xa;
	else if (ch >= 'A' && ch <= 'F')
		return ch - 'A' + 0xA;
	else
		throw std::bad_cast();
}	

template <typename Return, typename Iterator>
inline Return hex2ord(Iterator beg, Iterator end)
{
	Return r = 0;
	for (Iterator i = beg; i != end; ++i)
	{
		Return v = hex2ord(*i);
		r = (r << 4) | v;
	}
	return r;
}

inline char ord2hex(char v)
{
	if (v >= 0 && v <= 9)
		return v + '0';
	else if (v >= 10 && v <= 15)
		return v - 10 + 'a';
	throw std::bad_cast();
}

inline char * ord2hex(char v, char *r)
{
	*r++ = ord2hex((unsigned char)v / 16);
	*r++ = ord2hex((unsigned char)v % 16);
	return r;
}

}} // namespace alpha::utility
